package session

import (
	"errors"
	"gitee.com/haozing/wim/session/iface"
	"gitee.com/haozing/wim/session/internal"
	"github.com/golang/glog"
	"sync"
)

type server struct {
	authManager sync.Map            //根据authKeyId生成的Map
	event       iface.IEventHandler //自定义实现的事件
}

func NewServer(e iface.IEventHandler) iface.IServer {
	return &server{
		authManager: sync.Map{},
		event:       e,
	}
}

// MsgHandle 接收前端网关(comet)和异步推送(sync)的信息
func (s *server) MsgHandle(m iface.IMsgHandle) error {

	var AuthUser *internal.AuthUser

	if m.AuthKeyId() == 0 {
		return errors.New("没有设置AuthKeyId")
	}
	if a, ok := s.authManager.Load(m.AuthKeyId()); !ok {
		AuthUser = internal.MakeAuthUser(m.AuthKeyId(), s)
		s.authManager.Store(m.AuthKeyId(), AuthUser)
		err := s.startAuthUser(AuthUser)
		if err != nil {
			return err
		}
	} else {
		AuthUser, _ = a.(*internal.AuthUser)
	}

	glog.Infof("start MsgHandle...authKeyId:%d", m.AuthKeyId())
	return AuthUser.MsgJoin(m.Attachment())
}
func (s *server) startAuthUser(AuthUser iface.IAuthUser) error {
	AuthUser.Start()
	return nil
}
func (s *server) Event() iface.IEventHandler {
	return s.event
}
func (s *server) GetAuthUser(authKeyId int64) iface.IAuthUser {
	if vv, ok := s.authManager.Load(authKeyId); ok {
		return vv.(*internal.AuthUser)
	} else {
		return nil
	}
}
func (s *server) CloseAuthUser(authKeyId int64) {
	if vv, ok := s.authManager.Load(authKeyId); ok {
		vv.(*internal.AuthUser).Stop()
		s.authManager.Delete(authKeyId)
	}
}
